from fastapi import APIRouter, Depends
from sqlalchemy import func
from sqlalchemy.orm import Session
from ..db import get_db
from .. import models
from ..security import get_current_user

router = APIRouter()

@router.get("/dashboard")
def dashboard(db: Session = Depends(get_db), current=Depends(get_current_user)):
    total = db.query(func.count(models.Issue.id)).filter(models.Issue.owner_id == current.id).scalar() or 0
    in_progress = db.query(func.count(models.Issue.id)).filter(models.Issue.owner_id == current.id, models.Issue.status == "doing").scalar() or 0
    todo = db.query(func.count(models.Issue.id)).filter(models.Issue.owner_id == current.id, models.Issue.status == "todo").scalar() or 0
    done = db.query(func.count(models.Issue.id)).filter(models.Issue.owner_id == current.id, models.Issue.status == "done").scalar() or 0
    return {"total": total, "todo": todo, "doing": in_progress, "done": done}

@router.get("/dashboard/folders")
def dashboard_folders(db: Session = Depends(get_db), current=Depends(get_current_user)):
    # per-folder counts for current user
    rows = (
        db.query(
            models.Folder.id.label("folder_id"),
            models.Folder.name.label("name"),
            func.count(models.IssueFolder.issue_id).label("count"),
        )
        .outerjoin(models.IssueFolder, models.IssueFolder.folder_id == models.Folder.id)
        .outerjoin(models.Issue, models.Issue.id == models.IssueFolder.issue_id)
        .filter(models.Folder.owner_id == current.id)
        .group_by(models.Folder.id)
        .all()
    )

    # unassigned issues for current user
    assigned_sq = db.query(models.IssueFolder.issue_id).subquery()
    unassigned = (
        db.query(func.count(models.Issue.id))
        .filter(models.Issue.owner_id == current.id)
        .filter(~models.Issue.id.in_(assigned_sq))
        .scalar()
        or 0
    )

    folders = [
        {"folder_id": r.folder_id, "name": r.name, "count": int(r.count or 0)} for r in rows
    ]
    return {"folders": folders, "unassigned": int(unassigned)}
